/*
WhirlMon - Whirlpool.net forums thread monitor
Copyright (C) 2012  Lindsay Mathieson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dyndns.blackpaw.whirlmon;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 
 * @author lindsay
 */
public class WPThread implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2790315054124989913L;

	static public class List extends ArrayList<WPThread> {

		/**
		 * 
		 */
		private static final long serialVersionUID = -3542889434145369539L;

		public WPThread findThread(WPThread th) {
			return findThreadById(th.id);
		}

		public WPThread findThreadById(long id) {
			for (WPThread th : this) {
				if (th.id == id) {
					return th;
				}
			}
			return null;
		}

	}

	public long id;
	public String title;
	public int replies;
	public int unread;
	public int lastRead;
	public int lastPage;
	public long lastId;
	public String lastName;
	public Date lastDate;
	public long forumId;
	public String forumName;

	static public WPThread.List getWatched(String apiKey, boolean unread,
			boolean ignoreOwn) throws Exception {
		WPThread.List threads = new List();

		long userId = -1;
		String apiKeys[] = apiKey.split("-");
		if (apiKeys.length > 0) {
			try {
				userId = Long.parseLong(apiKeys[0]);
			} catch (Exception x) {
				userId = -1;
			}
		}

		// Date Format
		// 2012-04-07T17:11:25+1000
		String gmtFormat = "yyyy-MM-dd'T'HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(gmtFormat);

		JSONObject jo = Json.getJSON(apiKey, "&get=watched&watchedmode="
				+ (unread ? "0" : "1"));
		JSONArray jaWatched = jo.getJSONArray("WATCHED");
		for (int i = 0; i < jaWatched.length(); i++) {
			JSONObject joThread = jaWatched.getJSONObject(i);

			WPThread th = new WPThread();
			th.id = joThread.getLong("ID");
			th.title = joThread.getString("TITLE");
			th.replies = joThread.getInt("REPLIES");
			th.unread = joThread.getInt("UNREAD");
			th.lastRead = joThread.getInt("LASTREAD");
			th.lastPage = joThread.getInt("LASTPAGE");
			th.lastId = ((JSONObject) joThread.get("LAST")).getLong("ID");
			th.lastName = ((JSONObject) joThread.get("LAST")).getString("NAME");
            th.forumId = joThread.getLong("FORUM_ID");
            th.forumName = joThread.getString("FORUM_NAME");

			String sDate = joThread.getString("LAST_DATE");
			th.lastDate = sdf.parse(sDate);
			if (ignoreOwn && (userId > 0 && userId == th.lastId)) {
				// Ignore threads we last posted in
				th.unread = 0;
				if (unread)
					continue;
			}

			threads.add(th);
		}

		return threads;
	}

	static public WPThread.List getRecent(String apiKey, boolean ignoreOwn)
			throws Exception {
		WPThread.List threads = new List();

		long userId = -1;
		String apiKeys[] = apiKey.split("-");
		if (apiKeys.length > 0) {
			try {
				userId = Long.parseLong(apiKeys[0]);
			} catch (Exception x) {
				userId = -1;
			}
		}

		// Date Format
		// 2012-04-07T17:11:25+1000
		String gmtFormat = "yyyy-MM-dd'T'HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(gmtFormat);

		JSONObject jo = Json.getJSON(apiKey, "&get=recent");
		JSONArray jaRecent = jo.getJSONArray("RECENT");
		for (int i = 0; i < jaRecent.length(); i++) {
			JSONObject joThread = jaRecent.getJSONObject(i);

			long id = ((JSONObject) joThread.get("LAST")).getLong("ID");
			if (ignoreOwn && userId != -1 && userId == id)
				continue;

			WPThread th = new WPThread();
			th.id = joThread.getLong("ID");
			th.title = joThread.getString("TITLE");
			th.replies = joThread.getInt("REPLIES");
			// th.unread = joThread.getInt("UNREAD");
			// th.lastRead = joThread.getInt("LASTREAD");
			// th.lastPage = joThread.getInt("LASTPAGE");
			th.lastId = id;
			th.lastName = ((JSONObject) joThread.get("LAST")).getString("NAME");
	        th.forumId = joThread.getLong("FORUM_ID");
            th.forumName = joThread.getString("FORUM_NAME");

			String sDate = joThread.getString("LAST_DATE");
			th.lastDate = sdf.parse(sDate);

			threads.add(th);
		}

		return threads;
	}

	static public void MarkThreadRead(String apiKey, long id) throws Exception {
		Json.getJSON(apiKey, "&watchedread=" + id);
	}

	static public boolean EqualMsgs(WPThread.List w1, WPThread.List w2) {
		// different thread counts?
		if (w1.size() != w2.size())
			return false;

		// Does w1 have threads not in w2
		// OR do they have different msg counts
		for (WPThread th1 : w1) {
			WPThread w = w2.findThread(th1);
			if (w == null)
				return false;
			if (w.replies != th1.replies)
				return false;
		}

		// Does w2 have threads not in w1 etc
		for (WPThread th2 : w2) {
			WPThread w = w1.findThread(th2);
			if (w == null)
				return false;
			if (w.replies != th2.replies)
				return false;
		}

		// identical
		return true;
	}

	static public boolean NewMessagesInW2(WPThread.List w1, WPThread.List w2) {
		// Does w2 have more threads
		if (w2.size() > w1.size())
			return true;

		// Does w2 have threads not in w1
		for (WPThread th2 : w2) {
			// Find thread in w1
			WPThread th1 = null;
			for (int i = 0; i < w1.size(); i++) {
				WPThread th = w1.get(i);
				if (th.id == th2.id) {
					th1 = th;
					break;
				}
			}
			if (th1 == null)
				return true;
			// does th2 have more new messages that th1
			if (th2.replies > th1.replies)
				return true;
		}

		return false;
	}
}
